Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

224
Vistas
JavaScript Range setStart not working on "Bold" Text

I want to set cursor/caret position manually. This is working fine if contents are only text in a contenteditable. But if content contains text with bold, underline etc then the it is not working and it throws and error

Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 2.

in below sample if you enter "0" in Node number then the cursor moves. But if you enter "1" in Node number then it throws error. What's wrong in it to move cursor over bold text.

  button.onclick = () => {
    let range = new Range();

    range.setStart(p.childNodes[node.value], start.value);
  
    document.getSelection().removeAllRanges();
    document.getSelection().addRange(range);
  };
<p id="p" contenteditable="true">This is <b>bold</b></p>

Cursor Position <input id="start" type="number" value="2">  Node number <input id="node" type="number" value="0">
<button id="button">Mover Cursor</button>

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In your example, p.childNodes[1] resolves to the node <b>bold</b>. You can only jump to the start or end of its text (index 0 and 1), as you are viewing the node as a whole. If you want to set the cursor within this node, you have to access its actual textual contents.

While not working for more complex cases, this should push you in the right direction:

let childNode = p.childNodes[node.value];
while (childNode.hasChildNodes()) {
  childNode = childNode.firstChild;
}
    
range.setStart(childNode, start.value);
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda